from typing import List

from fastapi import APIRouter, Depends
import json
from sqlalchemy import select, desc, func, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from apis.deps import get_db
from schemas import CaseListUpdate, CaseListCreate, CaseListOut as CaseList, Result, ResultPlus
from crud import caseList
from utils import resp_200, IdNotExist
from models import CaseList as CaseListModel

router = APIRouter()


@router.post("/create_caseList", response_model=Result, summary="新增用例列表")
async def create_caseList(caseList_in: CaseListCreate, db: AsyncSession = Depends(get_db)):
    await caseList.create(db=db, obj_in=caseList_in)
    return resp_200(msg=f"成功添加用例列表")


@router.get("/", response_model=ResultPlus[CaseList], summary="查询用例列表")
async def get_caseList(pageIndex: int = 1, pageSize: int = 10, queryName: str = '', projectId: int = 0,
                       db: AsyncSession = Depends(get_db)):
    sql1 = select(CaseListModel).offset((pageIndex - 1) * pageSize).limit(pageSize).where(
        CaseListModel.name.like(f'%{queryName}'), CaseListModel.projectId == projectId).order_by(desc(CaseListModel.id))
    result1 = await db.execute(sql1)
    caseList = result1.scalars().all()
    sql2 = select(func.count(distinct(CaseListModel.id))).where(CaseListModel.projectId == projectId)
    count = await db.scalar(sql2)
    return resp_200(data={"count": count, "list": caseList}, msg=f"查询成功")


@router.put('/update_caseList/{id}', response_model=Result, summary="通过id更新用例列表信息")
async def update_caseList(id: int, caseList_in: CaseListUpdate, db: AsyncSession = Depends(get_db)):
    row = await caseList.update(db, id, obj_in=caseList_in)
    return resp_200(msg=f"成功更新用例列表信息")


@router.delete('/delete_caseList/{id}', response_model=Result, summary="通过id删除用例列表信息")
async def delete_caseList(id: int, db: AsyncSession = Depends(get_db)):
    row = await caseList.remove(db, id)
    return resp_200(msg=f"成功删除用例列表信息")


@router.put('/updateStatus/{id}', response_model=Result, summary='通过id更新用例列表状态')
async def updateStatus(id: int, db: AsyncSession = Depends(get_db)):
    caseList = await db.get(CaseListModel, id)
    caseList.status = not caseList.status
    await db.commit()
    return resp_200(msg="用例列表状态更新成功")
